package com.healthy.intercepter;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.healthy.util.Dateutil;

public class BUnLogin implements HandlerInterceptor{

	/**
     * 该方法是在Controller执行之前调用的
     * 若该方法返回true:则会继续执行postHandle和afterCompletion
     * 若该方法返回false:整个请求结束
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 获得用户请求的URI
        String requestURI = request.getRequestURI();//URI=/web/css/home.css 即工程名web+目标资源路径
        String requestPath = request.getServletPath();//URL=/css/home.css 即目标资源名称
        // if(String.indexOf("/login") > 0) = true时该String包含"/login"
        Object role = request.getSession().getAttribute("role");  // role=user/admin
        Object u = null;
        if("admin".equals( (String)role) ){
        	u = request.getSession().getAttribute("admin");   
        }else if("user".equals( (String)role) ){
        	u = request.getSession().getAttribute("user");   
        }
        if (u == null) {
            response.setHeader("content-type", "application/json;charset=utf8");
            JSONObject json = unLogin(request);
            response.getWriter().write(json.toJSONString());
//            System.out.println("reject: " + requestURI);
            System.out.println("deny: " + requestPath);
            return false;
        }
        return true;
    }

    public JSONObject unLogin(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        json.put("statusCode", -1);
        json.put("msg", "您还未登陆，无法操作");
        json.put("log", "时间：" + Dateutil.getCurrentDateText() + " IP:" + getIpAddress(request));
        return json;
    }

    /**
     * 该方法是在Controller执行之后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        
    }

    /**
     * 该方法在整个请求完成之后执行，主要用于清理资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    // 获取IP
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
